import { Box, MenuItem, Typography } from '@mui/material';
import React, { useCallback, useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import Web3 from 'web3';

import Config, { GoogleCloudProject } from '../../config';
import { GFSInputSelectBase } from '../shared/forms';
import GlobalEvents from '../../hooks/events';
import { Network } from '../../api/token/token-manager';
import { useGetThemeStateStore } from '../../stores/theme';
import { MenuPro } from '../../components/global';


var upData:Function;
GlobalEvents.events.addListener("toSwitchNet",async (obj)=>{
    // {network:Network,callback:Function}  obj
    console.log("toSwitchNet-id",obj.network);
    if(upData){
        try{
            let aa = await upData(null,obj.network);
            if(obj.callback) obj.callback(aa);
        }catch(err){
            console.log("err=",err)
        }
    }
    // onChange(null,0);
})



export interface IChainOption {
    name: string;
    rpc?: string;
    evm_id?: string;
    logo: string;
}

const SwitchChain = () => {
    const [value, setValue] = useState('');
    const [chainList, setChainList] = useState<{ [p: string]: IChainOption }>({});
    const [isChainUpdated, setIsChainUpdated] = useState<boolean>(false);
    const {mode,isLight,setMode,color1,bgColor,bgColor1,bgColor0,txtColor,txtColor3} = useGetThemeStateStore();
    const handleChainChanged = useCallback(() => {

        console.log("handleChainChanged-isChainUpdated",isChainUpdated);


        setIsChainUpdated(!isChainUpdated);

        GlobalEvents.events.emit('changeNet',{});

    }, [isChainUpdated]);

    var listener;

    useEffect(() => {
        (window['ethereum'] as any).on('chainChanged', handleChainChanged);
        return () => {
            (window['ethereum'] as any).removeListener('chainChanged', handleChainChanged);
        };
    }, [handleChainChanged]);

    useEffect(() => {
        setChainList({
            ETHEREUM: {
                id:'ethereum',
                name: 'Ethereum',
                rpc:
                    Config.getEnvironment() == GoogleCloudProject.LIVE
                        ? 'https://mainnet.infura.io/v3/53a4ce5646b3454f96d45d2ad0529e51'
                        : 'https://goerli.infura.io/v3/53a4ce5646b3454f96d45d2ad0529e51',
                evm_id: Config.getEnvironment() == GoogleCloudProject.LIVE ? '0x1' : '0x5',
                logo: '/icon_ethereum.svg'
                // logo: 'https://dev.cloud.gfs.xld.finance/images/networks/ethereum.png'
                // logo: 'https://dev.cloud.xld.finance/images/blockchains/ethereum.png'
            },
            POLYGON: {
                id:'polygon',
                name: 'Polygon',
                rpc:
                    Config.getEnvironment() == GoogleCloudProject.LIVE
                        ? 'https://polygon-rpc.com/'
                        : 'https://matic-mumbai.chainstacklabs.com/',
                evm_id: Config.getEnvironment() == GoogleCloudProject.LIVE ? '0x89' : '0x13881',
                logo: '/icon_polygon.svg'
                // logo: 'https://dev.cloud.gfs.xld.finance/images/networks/polygon.png'
            },
            BSC: {
                id:'bnb_chain',
                name: 'Binance Smart Chain',
                rpc:
                    Config.getEnvironment() == GoogleCloudProject.LIVE
                        ? 'https://bsc-dataseed1.binance.org/'
                        : 'https://data-seed-prebsc-1-s1.binance.org:8545/',
                evm_id: Config.getEnvironment() == GoogleCloudProject.LIVE ? '0x38' : '0x61',
                logo: isLight?'/icon_BSC_w.svg':'/icon_BSC.svg',
            }
        });
    }, [isLight]);

    useEffect(() => {
        if (Object.keys(chainList)?.length > 0) {
            const web3 = new Web3();
            const currentNetwork = web3.utils.toHex((window.ethereum as any).networkVersion);
            let isInList = false;

            Object.entries(chainList).forEach(([key, value]) => {
                if (value?.['evm_id'] === currentNetwork) {
                    setValue(key);
                    isInList = true;
                }
            });
            if (!isInList) {
                setValue('');
            }
        }
    }, [chainList, isChainUpdated]);

    const getNetKey = (net:Network)=>{
        let _key:string = "";
        Object.entries(chainList).forEach(([key, value]) => {
            if (value?.['id'] === net.id) {
                _key = key;
            }
        });
        if(_key.length!=0){
            return _key
        }

        return null;
    }

    const onChange = async (event,net:Network=null) => {
        console.log("onChange--",event)
        const value = event ? event.target.value : getNetKey(net);
        const networkId = chainList[value]?.evm_id;
        if(net){
            const web3 = new Web3();
            const currentNetwork = web3.utils.toHex((window.ethereum as any).networkVersion);

            // console.log("currentNetwork",networkId , currentNetwork);
            if(networkId == currentNetwork) return true;
        }

        // console.log("networkId=",networkId,value,chainList)
        if (!networkId) return false;

        const ethereum = window['ethereum'] as any;
        const web3 = new Web3();
        try {
            let aa = await ethereum.request({
                method: 'wallet_switchEthereumChain',
                params: [{ chainId: web3.utils.toHex(networkId) }]
            });


            setValue(value);
            toast.success(
                'You have successfully changed network to ' + chainList[value].name + ' network',
                {
                    theme: mode,
                    bodyStyle:{
                        color:txtColor,
                    },
                }
            );
            GlobalEvents.events.emit('changeNet',{});
            return true;
        } catch (e) {
            if (e?.code === 4902) {
                try {
                    try {
                        await ethereum.request({
                            method: 'wallet_addEthereumChain',
                            params: [
                                {
                                    chainId: chainList[value]?.evm_id,
                                    rpcUrls: [chainList[value]?.rpc],
                                    chainName: chainList[value]?.name
                                }
                            ]
                        });
                    } catch {
                        toast.error('Error when adding network! Please try again!', {
                            theme: 'dark'
                        });
                        return false;
                    }

                    await ethereum.request({
                        method: 'wallet_switchEthereumChain',
                        params: [{ chainId: web3.utils.toHex(networkId) }]
                    });



                    setValue(value);
                    toast.success(
                        'You have successfully changed network to ' +
                            chainList[value].name +
                            ' network',
                        {
                            theme: mode
                        }
                    );
                    GlobalEvents.events.emit('changeNet',{});
                    return true;
                } catch {
                    return false;
                }
            }
            toast.error('Error when changing network! Please try again!', { theme: 'dark' });
        }
    };

    upData = onChange;



    return (
        <GFSInputSelectBase
            // IconComponent={() => (
            //     <Box
            //         component="img"
            //         sx={{
            //             width: '10px',
            //             position: 'absolute',
            //             right: '8px',
            //             top: '45%',
            //             // transform: 'translateY(-50%)',
            //             pointerEvents: 'none',
            //
            //         }}
            //         alt="Icon"
            //         src={'/dropdown.svg'}
            //     />
            // )}
            value={value}
            onChange={onChange}
            MenuProps={MenuPro({color1,bgColor,bgColor1})}

            sx={{
                // background:'red !important',
                border:0,
                color:txtColor,
                minWidth: '50px',


                '& .MuiSelect-select': {
                    border: '1px solid transparent !important',

                    height: '36px',
                    padding: '9px 2px 9px 8px',
                    background:bgColor1+' !important',
                },
                '&:hover':{
                    '& .MuiSelect-select':{

                        border: '1px solid transparent !important',
                        backgroundClip: 'padding-box, border-box !important',
                        backgroundOrigin: 'padding-box, border-box !important',
                        backgroundImage: 'linear-gradient(to right, '+bgColor+', '+bgColor+'), linear-gradient(to right, #0CAFE3, #3358B8) !important',
                    },
                },
                '&.MuiOutlinedInput-root': {
                    background: bgColor+' !important',
                    border: 'solid 1px transparent',
                    backgroundOrigin: 'border-box',
                    borderRadius: '12px'
                },
                '& .MuiInputBase-input': {
                    // background: bgColor1,
                    background:'transparent !important',
                },
                '& svg':{
                    fill:txtColor,
                },

            }}
            displayEmpty
            renderValue={
                value !== ''
                    ? (cur: string) => (
                          <Box  alignItems={'center'}>
                              {chainList?.[cur]?.logo && (
                                  <Box
                                      component="img"
                                      sx={{
                                          height: 18,
                                          width: 18,
                                          display:'block',
                                      }}
                                      alt="Icon"
                                      src={chainList[cur].logo}
                                  />
                              )}
                          </Box>
                      )
                    : () => (
                          <Box  alignItems={'center'}>
                              <Box
                                  component="img"
                                  sx={{
                                      height: 18,
                                      width: 18,
                                      display:'block',
                                  }}
                                  alt="Icon"
                                  src={
                                      '/icon_ethereum.svg'
                                  }
                              />
                          </Box>
                      )
            }
        >
            {/*<div style={{backgroundColor:bgColor,padding:'16px 0'}}>*/}
                {Object.entries(chainList).map(([key, option]) => (
                    <MenuItem key={key} value={key} disabled={!option?.evm_id} sx={{
                        '&:hove':{
                            // background:bgColor1+"!important",
                            // color:'red',
                        }
                    }} >
                        <Box display={'flex'} gap={'10px'} p={1} alignItems={'center'} >
                            <Box
                                component="img"
                                sx={{
                                    height: 18,
                                    width: 18
                                }}
                                alt="Icon"
                                src={option.logo}
                            />
                            <Box component={'span'} className={'mm-txt8'} sx={{ color: txtColor }}>{option.name}</Box>
                        </Box>
                    </MenuItem>
                ))}
            {/*</div>*/}
        </GFSInputSelectBase>
    );
};

export default SwitchChain;
